package com.shouer.doc.ui.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import com.shouer.doc.NotificationInterface;
import com.shouer.doc.R;
import com.shouer.doc.application.App;
import com.shouer.doc.common.util.VibratorUtil;
import com.shouer.doc.dao.AdviceReadRecord;
import com.shouer.doc.dao.AdviceReadRecordDao;
import com.shouer.doc.dao.DaoSession;
import com.shouer.doc.dialog.AdDialogUtil;
import com.shouer.doc.dialog.CommonDialogUtil;
import com.shouer.doc.dialog.RemoteLoginDialogUtil;
import com.shouer.doc.event.RemoteLoginEvent;
import com.shouer.doc.event.RongRemoteLoginEvent;
import com.shouer.doc.event.ShowAppTxtMsgMessage;
import com.shouer.doc.event.ShowOrderNotification;
import com.shouer.doc.event.UnReadCountEvent;
import com.shouer.doc.ui.login.LoginActivity;
import com.shouer.doc.ui.main.adapter.FragmentAdapter;
import com.shouer.doc.ui.main.presenter.IMainPresenter;
import com.shouer.doc.ui.main.presenter.MainPresenterImpl;
import com.shouer.doc.ui.main.response.QueryDocAdResponse;
import com.shouer.doc.ui.main.view.IMainView;
import com.shouer.doc.ui.neworder.NewOrderFragment;
import com.shouer.doc.ui.ordermanager.OrderManagerFragment;
import com.shouer.doc.ui.userinfo.UserInfoFragment;
import com.shouer.doc.widget.ShouerNotificationToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnPageChange;

/**
 * Created by ZXL on 2016/11/25.
 */

public class MainActivity extends FragmentActivity implements View.OnClickListener,IMainView{

    private App app;

    @BindView(R.id.fragment_viewpager)
    protected ViewPager viewPager;
    @BindView(R.id.tap1)
    protected View tap1;
    @BindView(R.id.tap2)
    protected View tap2;
    @BindView(R.id.tap3)
    protected View tap3;

    @BindView(R.id.unread_ico)
    protected View unReadIco;


    private ArrayList<Fragment> fragmentList;
    private long firstTime = -1;//连续点击两次返回的时间判断标识

    private IMainPresenter mPresenter;

    public void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);
        app= (App) getApplicationContext();
        if (!app.isUserLogin())
        {
            Intent loginIntent=new Intent(MainActivity.this, LoginActivity.class);
            startActivity(loginIntent);
            finish();
        }
        setContentView(R.layout.activity_main_layout);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initViewPagers();

        if (null!=getIntent().getData())
        {

            if (getIntent().getData().getPath().contains("neworder"))
            {
                viewPager.setCurrentItem(0);
            }else if (getIntent().getData().getPath().contains("healthrecord"))
            {
                viewPager.setCurrentItem(0);
            }else if (getIntent().getData().getPath().contains("conversationlist"))
            {
                viewPager.setCurrentItem(1);
            }
        }

        mPresenter=new MainPresenterImpl(this);
        mPresenter.queryDocAdInfo();
    }

    @Override
    public void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
        Log.i(MainActivity.class.getSimpleName(),"onNewIntent");
        if (!app.isUserLogin())
        {
            Intent loginIntent=new Intent(MainActivity.this, LoginActivity.class);
            startActivity(loginIntent);
            finish();
        }else
        {
            if (null!=intent.getData())
            {

                if (intent.getData().getPath().contains("neworder"))
                {
                    viewPager.setCurrentItem(0);
                }else if (intent.getData().getPath().contains("conversationlist"))
                {
                    viewPager.setCurrentItem(1);
                }
            }
        }

    }

    private void initViewPagers()
    {
        fragmentList=new ArrayList<>();
        fragmentList.add(new NewOrderFragment());
        fragmentList.add(new OrderManagerFragment());
        fragmentList.add(new UserInfoFragment());

        viewPager.setAdapter(new FragmentAdapter(getSupportFragmentManager(),fragmentList));
        tap1.setSelected(true);
    }

    @OnPageChange(value = {R.id.fragment_viewpager}, callback = OnPageChange.Callback.PAGE_SELECTED)
    public void onPageSelected(int selected) {
        switch (selected) {
            case 0:
                tap1.setSelected(true);
                tap2.setSelected(false);
                tap3.setSelected(false);
                break;
            case 1:
                tap1.setSelected(false);
                tap2.setSelected(true);
                tap3.setSelected(false);
                unReadIco.setVisibility(View.GONE);
                break;
            case 2:
                tap1.setSelected(false);
                tap2.setSelected(false);
                tap3.setSelected(true);
                break;
        }
    }



    @OnClick(value = {R.id.tap1,R.id.tap2,R.id.tap3})
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.tap1:
                viewPager.setCurrentItem(0);
                tap1.setSelected(true);
                tap2.setSelected(false);
                tap3.setSelected(false);
                break;
            case R.id.tap2:
                viewPager.setCurrentItem(1);
                tap1.setSelected(false);
                tap2.setSelected(true);
                tap3.setSelected(false);
                unReadIco.setVisibility(View.GONE);
                break;
            case R.id.tap3:
                viewPager.setCurrentItem(2);
                tap1.setSelected(false);
                tap2.setSelected(false);
                tap3.setSelected(true);
                break;
            case R.id.dialog_left_btn:
                CommonDialogUtil.getInstance().dismiss();
                break;
            case R.id.dialog_right_btn:
                CommonDialogUtil.getInstance().dismiss();
                app.loginOut();
                Intent loginIntent=new Intent(this, LoginActivity.class);
                startActivity(loginIntent);
                finish();
                break;
            case R.id.dialog_center_btn:
                CommonDialogUtil.getInstance().dismiss();
                Intent intent=new Intent(this, LoginActivity.class);
                startActivity(intent);
                EventBus.getDefault().post(new RemoteLoginEvent());
                break;
            case R.id.remotelogin_center_btn:
                CommonDialogUtil.getInstance().dismiss();
                Intent intent1=new Intent(this, LoginActivity.class);
                startActivity(intent1);
                EventBus.getDefault().post(new RemoteLoginEvent());
                finish();
                break;
        }
    }

    public void loginOut()
    {
        CommonDialogUtil.getInstance().showMessage(this,this,"退出当前账号","取消","确定",0);
    }

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (firstTime < 0 || (secondTime - firstTime) > 400) {
            Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            firstTime = secondTime;
        } else {
            System.exit(0);
        }
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        mPresenter.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RongRemoteLoginEvent event)
    {
        RemoteLoginDialogUtil.getInstance().show(this,this,"你的账号已经在其他设备登录请重新登录");
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ShowOrderNotification event)
    {
        if (app.isUserLogin())
        {
            ShouerNotificationToast.Builder builder=new ShouerNotificationToast.Builder(this);
            builder.setContent(event.getOrderMessage().getContent())
                    .setTitle((String) this.getPackageManager().getApplicationLabel(this.getApplicationInfo()))
                    .setDuration(Toast.LENGTH_LONG)
                    .setGravity(Gravity.TOP|Gravity.FILL_HORIZONTAL)
                    .setmView(R.layout.layout_heads_up_notification);
            builder.createToast().show();
            VibratorUtil.Vibrate(this,100);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UnReadCountEvent event) {
        Log.i(MainActivity.class.getSimpleName(),"UnReadCountEvent");
        if (!tap2.isSelected()&&event.getUnReadCount()>0)
        {
            unReadIco.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ShowAppTxtMsgMessage event) {
        if (app.isUserLogin()&&app.getUserDocInfo().getRecordAccessRight()==1) {
            if (event.isShowToast())
            {
                Toast.makeText(this,event.getAppTxtMsgMessage().getContent(),Toast.LENGTH_SHORT).show();

            }else
            {
                NotificationInterface.sendAppTxtMsgNotification(MainActivity.this,event.getAppTxtMsgMessage().getContent());
            }

        }
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public String getUserId() {
        return app.getUserDocId();
    }

    @Override
    public DaoSession getDaoSession() {
        return app.getDaoSession();
    }

    @Override
    public void queryDocAdSuccess(QueryDocAdResponse response) {

        if (null!=response.getTopAdvertisement()&&null!=response.getTopAdvertisement().getAdvertisementId()&&!response.getTopAdvertisement().isReaded())
        {
            AdDialogUtil.getInstance().show(this,response.getTopAdvertisement());

            DaoSession daoSession=app.getDaoSession();
            AdviceReadRecordDao adviceReadRecordDao=daoSession.getAdviceReadRecordDao();
            AdviceReadRecord adviceReadRecord=new AdviceReadRecord(getUserId(),response.getTopAdvertisement().getAdvertisementId());
            long id=adviceReadRecordDao.insert(adviceReadRecord);
            Log.i(MainActivity.class.getSimpleName(),"是否已读记录值："+id);
        }
    }
}
